package cn.learn.config;

import cn.learn.domain.SysAccount;
import cn.learn.util.JsonUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

/**
 * 自定义策略
 *
 * @author huangyezhan
 * @version 1.0
 * @date 2020年07月23日23:34
 */
//@Component
public class MyOAuth2AuthenticationProcessingFilter extends OncePerRequestFilter {


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String token = request.getHeader("token-pms");
        if (token != null) {
            //解析token
            String              user      = URLDecoder.decode(token, "UTF-8");
            Map<String, Object> map       = JsonUtil.string2Map(user);
            String              principal = (String) map.get("principal");
            SysAccount account = new SysAccount();
            account.setAccountName(principal);

            List<String> authorities = (List<String>) map.get("authorities");
            String[]     strings     = authorities.toArray(new String[authorities.size()]);
            //填充authentication
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(account, null, AuthorityUtils.createAuthorityList(strings));
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            //authentication保存上下文中
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        chain.doFilter(request, response);
    }

}
